﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

    public class Printer
    {
        public void Print(int number)
        {
            Console.WriteLine(number);
        }
    }

    public class ThreadStartParams
    {
        public Printer Printer { get; set; }
        public EventWaitHandle WaitHandler { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Printer p           = new Printer();
            EventWaitHandle wh1 = new ManualResetEvent(true);
            EventWaitHandle wh2 = new ManualResetEvent(true);


            Thread t = new Thread(Thread2EntryPoint);
            t.IsBackground = true;
            t.Start(new ThreadStartParams(){Printer = p,WaitHandler = wh1});
            Thread t2 = new Thread(Thread3EntryPoint);
            t2.IsBackground = true;
            t2.Start(new ThreadStartParams(){Printer = p,WaitHandler = wh2});

            //t.Join();
            //t2.Join();

            ConsoleKey kInfo = Console.ReadKey().Key;
            while (kInfo != ConsoleKey.X)
            {
                if (kInfo == ConsoleKey.NumPad1)
                {
                    wh1.Set();
                }
                if (kInfo == ConsoleKey.NumPad2)
                {
                    wh1.Reset();
                }
                if (kInfo == ConsoleKey.NumPad3)
                {
                    wh2.Set();
                }
                if (kInfo == ConsoleKey.NumPad4)
                {
                    wh2.Reset();
                }

                kInfo = Console.ReadKey().Key;
            }
        }

        private static void Thread2EntryPoint(object o)
        {
            ThreadStartParams p = (ThreadStartParams)o;

            for (int i = Int32.MaxValue; i > 0; i--)
            {
                p.WaitHandler.WaitOne();
                p.Printer.Print(i);
            }
        }

        private static void Thread3EntryPoint(object o)
        {
            ThreadStartParams p = (ThreadStartParams)o;

            for (int i = 0; i < Int32.MaxValue; i++)
            {
                p.WaitHandler.WaitOne();
                p.Printer.Print(i);
            }
        }
    }
}
